import { defineStore } from "pinia";
import { ElMessage, ElMessageBox } from "element-plus";
import common_util from "@/util/common_util.js"; // 确保您的API工具路径正确

export const useExamStore = defineStore("exam", {
  state: () => ({
    /**
     * @description 当前正在查看或操作的单个考核的详细信息
     */
    currentExam: null,

    /**
     * @description 考核列表，用于展示给管理员、教师或学生
     */
    exams: [],

    /**
     * @description 当前考核下的所有试题和选项
     */
    questions: [],
    /**
     * @description 当前考核下的所有答卷
     */
    submissions: [],

    /**
     * @description 当前正在查看的单个学生答卷的详细信息
     */
    submission: null,

    /**
     * @description 用于分页的总条目数
     */
    total: 0,
    draftCount: 0,

    /**
     * @description 加载状态，用于在API请求期间显示加载动画
     */
    loading: false,
    // ...在 state: () => ({ ... }) 内部
    /**
     * @description 当前教师创建的考核列表
     * @type {Array<object>}
     */
    teacherExams: [],
  }),
  // getters
  getters: {
    // 可以添加一些计算属性，例如计算试题总分等
    totalPoints: (state) => {
      if (!state.questions || state.questions.length === 0) {
        return 0;
      }
      return state.questions.reduce(
        (sum, q) => sum + (q.examQuestion?.points || 0),
        0
      );
    },
  },

  // src/stores/exam.js

  // ... state 和 getters 部分保持不变 ...

  actions: {
    // =================================================================
    // 考核管理 (Exam Management)
    // =================================================================

    /**
     * @description 创建一个新的考核
     * @param {object} examData - 包含创建考核所需数据的对象
     * @param {function} [onSuccess] - 成功时执行的回调函数
     * @param {function} [onFailure] - 失败时执行的回调函数
     */
    createExam(examData, onSuccess, onFailure) {
      this.loading = true;
      common_util.post(
        "/api/exams",
        examData,
        {},
        (data) => {
          ElMessage.success("考核创建成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`创建考核失败: ${message}`);
          if (onFailure) onFailure(message);
          this.loading = false;
        }
      );
    },

    /**
     * @description 更新指定ID的考核信息
     * @param {number} examId - 要更新的考核ID
     * @param {object} examData - 更新后的考核数据
     * @param {function} [onSuccess] - 成功回调
     */
    updateExam(examId, examData, onSuccess) {
      this.loading = true;
      common_util.put(
        `/api/exams/${examId}`,
        examData,
        {},
        (data) => {
          ElMessage.success("考核更新成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`更新考核失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 逻辑删除一个考核
     * @param {number} examId - 要删除的考核ID
     * @param {function} [onSuccess] - 成功回调
     */
    deleteExam(examId, onSuccess) {
      ElMessageBox.confirm("此操作将永久删除该考核, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          common_util.delete(
            `/api/exams/${examId}`,
            {},
            (data) => {
              ElMessage.success("考核删除成功!");
              // 从本地状态中移除已删除的考核
              this.exams = this.exams.filter((exam) => exam.exam.id !== examId);
              if (onSuccess) onSuccess(data);
              this.loading = false;
            },
            (message) => {
              ElMessage.error(`删除考核失败: ${message}`);
              this.loading = false;
            }
          );
        })
        .catch(() => {
          ElMessage.info("已取消删除");
        });
    },

    /**
     * @description 根据条件查询考核列表
     * @param {object} params - 筛选条件
     */
    // fetchExams(params = {},onSuccess) {
    //   this.loading = true;
    //   common_util.get(
    //     "/api/exams",
    //     params,
    //     (data, total) => {
    //       console.log("data:", data);
    //       console.log("total:", total);
    //       if (onSuccess) onSuccess(data);
    //       this.exams = data;
    //       this.total = total; // 假设后端没有返回 total 字段，我们自己计算
    //       this.loading = false;
    //     },
    //     (message) => {
    //       ElMessage.error(`获取考核列表失败: ${message}`);
    //       this.loading = false;
    //     }
    //   );
    // },
    fetchExams(params = {}, onSuccess, onFailure) {
      this.loading = true;
      common_util.get(
        "/api/exams",
        params,
        (data, total) => {
          // 确保 data 是一个数组
          const responseData = Array.isArray(data) ? data : [];

          // 兼容处理：如果后端返回的 total 是 null 或 undefined，则使用 data 数组的长度
          const responseTotal = (total === null || typeof total === 'undefined')
            ? responseData.length
            : total;

          // 更新 state
          this.exams = responseData;
          this.total = responseTotal;

          this.loading = false;
          // 执行成功回调
          if (onSuccess) onSuccess(responseData, responseTotal);
        },
        (message) => {
          ElMessage.error(`获取考核列表失败: ${message}`);
          this.loading = false;
          // 执行失败回调
          if (onFailure) onFailure(message);
        }
      );
    },
    fetchExamById(examId, onSuccess, onFailure) {
      this.loading = true; // 开始请求，设置加载状态为true
      common_util.get(
        `/api/exams/${examId}`, // API 路由
        {}, // GET 请求的参数，这里为空
        (data) => {
          // 请求成功的回调
          this.currentExam = data; // 将返回的数据存入 state 的 currentExam
          ElMessage.success("获取考核信息成功！");
          if (onSuccess) onSuccess(data); // 如果有成功回调，则执行
          this.loading = false; // 结束请求，设置加载状态为false
        },
        (message) => {
          // 请求失败的回调
          ElMessage.error(`获取考核信息失败: ${message}`);
          if (onFailure) onFailure(message); // 如果有失败回调，则执行
          this.loading = false; // 结束请求，设置加载状态为false
        }
      );
    },

    // =================================================================
    // 试题管理 (Question Management)
    // =================================================================

    /**
     * @description 根据考核ID获取所有试题
     * @param {object} params - 包含 examId, pageNo, pageSize 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    fetchQuestionsByExamId(params, onSuccess) {
      this.loading = true;
      this.questions = []; // 请求前先清空旧数据
      this.currentExam = null; // 清空旧的考核信息
      const { examId, pageNo = 1, pageSize = -1 } = params; // 默认不分页
      common_util.get(
        `/api/exams/${examId}/questions`,
        { pageNo, pageSize },
        (data) => {
          this.questions = data;
          if (data && data.length > 0) {
            this.currentExam = data[0].exam;
            console.log("currentExam:", this.currentExam); // 打印 currentExam
          }
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取试题列表失败: ${message}`);
          this.loading = false;
        }
      );
    },

    /**
     * @description 向指定考核中添加一个新题目
     * @param {object} params - 包含 examId 和 questionData 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    addQuestionToExam(params, onSuccess) {
      const { examId, questionData } = params;

      // 已将请求从 GET 修改为 POST
      common_util.post(
        `/api/exams/${examId}/questions`, // 第一个参数: URL
        questionData,                     // 第二个参数: 请求体 (body)
        {},                               // 第三个参数: URL查询参数 (params)，这里为空
        (data) => {                       // 第四个参数: 成功回调
          ElMessage.success("添加题目成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {                     // 第五个参数: 失败回调
          ElMessage.error(`添加题目失败: ${message}`);
        }
      );
    },

    /**
     * @description 更新指定ID的题目信息
     * @param {object} params - 包含 questionId 和 questionData 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    updateQuestion(params, onSuccess) {
      const { questionId, questionData } = params;
      common_util.put(
        `/api/exams/questions/${questionId}`,
        questionData,
        {},
        (data) => {
          ElMessage.success("更新题目成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`更新题目失败: ${message}`);
        }
      );
    },

    /**
     * @description 逻辑删除一个题目
     * @param {number} questionId - 要删除的题目ID
     * @param {function} [onSuccess] - 成功回调
     */
    deleteQuestion(questionId, onSuccess) {
      common_util.delete(
        `/api/exams/questions/${questionId}`,
        {},
        (data) => {
          ElMessage.success("删除题目成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`删除题目失败: ${message}`);
        }
      );
    },

    /**
     * @description 向指定题目中添加一个新选项
     * @param {object} params - 包含 questionId 和 optionData 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    addOptionToQuestion(params, onSuccess) {
      const { questionId, optionData } = params;
      common_util.post(
        `/api/exams/questions/${questionId}`,
        optionData,
        {},
        (data) => {
          ElMessage.success("添加选项成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`添加选项失败: ${message}`);
        }
      );
    },

    /**
     * @description 逻辑删除一个选项
     * @param {number} optionId - 要删除的选项ID
     * @param {function} [onSuccess] - 成功回调
     */
    deleteOption(optionId, onSuccess) {
      common_util.delete(
        `/api/exams/options/${optionId}`,
        {},
        (data) => {
          ElMessage.success("删除选项成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`删除选项失败: ${message}`);
        }
      );
    },
    // =================================================================
    // 答卷与批改管理 (Submission & Grading Management)
    // =================================================================

    /**
     * @description 学生提交答卷
     * @param {object} submissionData - 包含 examId, studentId, submissionAnswers 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    submitExam(submissionData, onSuccess) {
      common_util.post(
        `/api/exams/submissions`,
        submissionData,
        {},
        (data) => {
          ElMessage.success("答卷提交成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`提交失败: ${message}`);
        }
      );
    },

    /**
     * @description 自动批改指定答卷的客观题
     * @param {number} submissionId - 答卷ID
     * @param {function} [onSuccess] - 成功回调
     */
    autoGradeSubmission(submissionId, onSuccess) {
      common_util.put(
        `/api/exams/submissions/${submissionId}/auto-grade`,
        {}, // PUT 请求没有 body，所以传空对象
        {},
        (data) => {
          ElMessage.success("客观题已自动评分！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`自动批改失败: ${message}`);
        }
      );
    },

    /**
     * @description 教师手动批改答案
     * @param {object} gradingData - 包含 teacherId 和 updateAnswerScoreDTOList 的对象
     * @param {function} [onSuccess] - 成功回调
     */
    manualGradeSubmission(gradingData, onSuccess) {
      common_util.put(
        `/api/exams/submissions/answers/manual-grade`,
        gradingData,
        {},
        (data) => {
          ElMessage.success("批改成功！");
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`批改失败: ${message}`);
        }
      );
    },

    /**
     * @description 根据答卷ID查询答卷详情
     * @param {number} submissionId - 答卷ID
     * @param {function} [onSuccess] - 成功回调
     */
    fetchSubmissionById(submissionId, onSuccess) {
      common_util.get(
        `/api/exams/submissions/${submissionId}`,
        {},
        (data) => {
          // 可以在这里将查询到的答卷详情存入 state，如果需要的话
          // this.currentSubmission = data;
          if (onSuccess) onSuccess(data);
        },
        (message) => {
          ElMessage.error(`查询答卷失败: ${message}`);
        }
      );
    },
    fetchDraftCount(params = {}) {
      // 我们只关心数量，所以设置 pageSize=1 即可，减少数据传输
      const queryParams = { ...params, pageNum : 1, pageSize : 1 }; 
      common_util.get(
        "/api/exams",
        queryParams,
        (data, total) => {
          // 后端返回的 total 字段可能不准确，我们以后端返回的 data 数组长度为准
          // 如果您的后端 total 字段是准确的，可以直接使用 total
          this.draftCount = total;
        },
        (message) => {
          // 即使获取失败，也只是数量显示不正确，不弹窗报错影响主流程
          console.error(`获取待发布考核数量失败: ${message}`);
          this.draftCount = 0; // 失败时重置为0
        }
      );
    },

    /**
    * @description 根据考核ID查询所有答卷（包括考生信息）
    * @param {object} params - 包含 examId 和可选的 pageNo, pageSize
    * @param {function} [onSuccess] - 成功回调
    */
    fetchSubmissionsByExamId(params, onSuccess) {
      const { examId, pageNo = 1, pageSize = 10 } = params;
      if (!examId) {
        ElMessage.error("查询答卷列表失败：必须提供考核ID。");
        return;
      }
      this.loading = true;
      common_util.get(
        `/api/exams/exams/${examId}/submissions`,
        { pageNo, pageSize },
        (data, total) => {
          // 将获取到的数据存储到 state 中
          this.$patch({
            submissions: data,
            total: total,
          });
          if (total <= 0) {
            ElMessage.warning("当前考核无人作答");
          }
          console.log("submissions:", data);
          if (onSuccess) onSuccess(data, total);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取答卷列表失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
     * @description 根据条件查询答卷列表
     * @param {object} params - 查询参数，如 pageNo, pageSize, studentId, examId
     * @param {function} [onSuccess] - 成功回调
     */
    fetchSubmissions(params = {}, onSuccess) {
      this.loading = true;
      let url = '/api/exams/submissions';
      // 区分是查某个学生的所有答卷，还是某个考核的所有答卷
      if (params.examId && params.studentId) {
        url = `/api/exams/${params.examId}/submissions`;
        delete params.examId; // studentId 会被自动作为查询参数
      }

      common_util.get(
        url,
        params,
        (data) => {
          // 可以在 state 中创建一个 submissions 数组来存储
          // this.submissions = data;
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`查询答卷列表失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
   * @description 提交答卷并立即请求自动判分（串联两个接口）
   * @param {object} submissionData - 提交的答卷数据
   * @param {function} [onSuccess] - 整个流程成功后的回调，返回自动判分结果
   * @param {function} [onFailure] - 失败回调
   */
    // submitAndGradeExam(submissionData, onSuccess, onFailure) {
    //   this.loading = true;
    //   // 第一步：调用已有的 submitExam 接口
    //   this.submitExam(submissionData,
    //     (submitResponse) => {
    //       // 提交成功后，从返回结果中获取 submissionId
    //       const submissionId = submitResponse?.examSubmission?.id;
    //       if (submissionId) {
    //         // 第二步：立即调用 autoGradeSubmission 接口
    //         this.autoGradeSubmission(submissionId,
    //           (gradeResponse) => {
    //             // 自动判分成功，执行最终的成功回调
    //             if (onSuccess) onSuccess(gradeResponse);
    //             this.loading = false;
    //           },
    //           (gradeError) => {
    //             // 自动判分失败
    //             if (onFailure) onFailure(gradeError);
    //             this.loading = false;
    //           }
    //         );
    //       } else {
    //         const errorMsg = "提交成功，但未能获取到答卷ID，无法进行自动判分。";
    //         ElMessage.error(errorMsg);
    //         if (onFailure) onFailure(errorMsg);
    //         this.loading = false;
    //       }
    //     },
    //     (submitError) => {
    //       // 提交答卷就失败了
    //       if (onFailure) onFailure(submitError);
    //       this.loading = false;
    //     }
    //   );
    // },
    /**
   * @description 提交答卷并立即请求自动判分（串联两个接口）
   * @param {object} submissionData - 提交的答卷数据
   * @param {function} [onSuccess] - 整个流程成功后的回调，返回自动判分结果
   * @param {function} [onFailure] - 失败回调
   */
    submitAndGradeExam(submissionData, onSuccess, onFailure) {
      this.loading = true;
      // 第一步：调用已有的 submitExam 接口
      this.submitExam(submissionData,
        (submitResponse) => {
          // 提交成功后，从返回结果中获取 submissionId
          const submissionId = submitResponse?.examSubmission?.id;
          if (!submissionId) {
            const errorMsg = "提交成功，但未能获取到答卷ID，无法进行自动判分。";
            ElMessage.error(errorMsg);
            if (onFailure) onFailure(errorMsg);
            this.loading = false;
            return;
          }

          // 第二步：并行调用客观题自动评分和主观题AI评分
          Promise.all([
            new Promise((resolve, reject) => this.autoGradeSubmission(submissionId, resolve, reject)),
            new Promise((resolve, reject) => this.aiGradeSubmission(submissionId, resolve, reject))
          ]).then(([autoGradeResponse, aiGradeResponse]) => {
            // 第三步：合并评分结果
            const gradeMap = new Map(autoGradeResponse.map(ans => [ans.questionId, ans]));

            aiGradeResponse.forEach(res => {
              // AI评分结果的结构是 { examAnswer: {...}, feedback: "..." }
              // 我们将 feedback 添加到答案对象中
              gradeMap.set(res.examAnswer.questionId, {
                ...res.examAnswer,
                feedback: res.feedback
              });
            });

            const finalResults = Array.from(gradeMap.values());
            ElMessage.success('答卷提交成功，所有题目已完成评分！');
            if (onSuccess) onSuccess(finalResults);
            this.loading = false;

          }).catch(error => {
            // 如果任一评分环节失败
            const errorMsg = `评分过程中出现错误: ${error || '请联系管理员'}`;
            ElMessage.error(errorMsg);
            if (onFailure) onFailure(errorMsg);
            this.loading = false;
          });
        },
        (submitError) => {
          // 提交答卷就失败了
          if (onFailure) onFailure(submitError);
          this.loading = false;
        }
      );
    },
    /**
     * @description 查询当前学生用户的所有相关考核
     * @param {function} [onSuccess] - 成功回调
     */
    fetchCurrentUserExams(onSuccess) {
      this.loading = true;
      common_util.get(
        `/api/exams/currentUserExams`,
        {},
        (data) => {
          // 成功后，可以直接在 state 中存储返回的数据对象
          // 例如: this.studentExams = data;
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取考核列表失败: ${message}`);
          this.loading = false;
        }
      );
    },
    fetchCurrentTeacherExams(onSuccess) {
      this.loading = true;
      common_util.get(
        `/api/exams/currentTeacherExams`,
        {},
        (data, total) => {
          this.teacherExams = Array.isArray(data) ? data : [];
          // 成功后，可以直接在 state 中存储返回的数据对象
          // 例如: this.studentExams = data;
          if (onSuccess) onSuccess(data, total);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取考核列表失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
 * @description 获取全部答卷，用于统计
 * @param {function} [onSuccess] - 成功回调
 */
    fetchAllSubmissions(onSuccess) {
      this.loading = true;
      common_util.get(
        '/api/exams/submissions',
        { pageSize: -1 }, // pageSize为-1表示获取全部数据
        (data) => {
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          ElMessage.error(`获取全部答卷失败: ${message}`);
          this.loading = false;
        }
      );
    },
    /**
    * @description AI 批改指定答卷的主观题
    * @param {number} submissionId - 要进行 AI 批改的答卷ID
    * @param {function} [onSuccess] - 成功回调，返回批改结果
    * @param {function} [onFailure] - 失败回调
    */
    aiGradeSubmission(submissionId, onSuccess, onFailure) {
      this.loading = true;
      common_util.put(
        `/api/exams/submissions/${submissionId}/ai-grade`,
        {}, // PUT请求，无请求体
        {}, // 无URL参数
        (data) => {
          ElMessage.success("AI 批改成功！");
          if (onSuccess) onSuccess(data);
          this.loading = false;
        },
        (message) => {
          // 根据要求，对于通用错误使用特定提示
          const errorMsg = message || "ai繁忙请稍后重试";
          ElMessage.error(`AI 批改失败: ${errorMsg}`);
          if (onFailure) onFailure(errorMsg);
          this.loading = false;
        }
      );
    },
  }
});